<template>
  <div id="popupbody" v-if="dialogVisible">
    <div class="popupbody-box">
      <div class="popupbody-title">
        <span>设备详情</span>
        <span class="el-icon-close" @click="closePOpup"></span>
      </div>
      <div class="popupbody-boxin" style="padding:10px 20px;" v-loading="loading"
           element-loading-text="设备连接中"
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)">
        <div v-if="successInfo" style="color:green;">
          状态：{{ successInfo }}
        </div>
        <div v-if="erroInfo" style="color:red;margin-bottom: 10px">
          状态：{{ erroInfo }}
          <el-button size="mini" icon="el-icon-refresh" class="ml-10" @click="refreshFn">重新获取设备连接</el-button>
        </div>
        <div class="table-box">
          <table class="pure-table" width="100%">
            <tr class="pure-table-odd">
              <td width="150">固件版本</td>
              <td id="cont-ver">
                <p>{{ infoOption ? infoOption.firmwareVer : '' }}</p>
                <el-button size="mini" class="ml-10" @click="updateDevice">更新</el-button>
                <el-button size="mini" @click="restartFn">重启</el-button>
              </td>
              <td width="150">识别号</td>
              <td>{{ infoOption ? infoOption.mac : '' }}</td>
            </tr>
            <tr>
              <td width="150">硬件版本</td>
              <td id="cont-hardware-ver">{{ infoOption ? infoOption.hardwareVer : '' }}</td>
              <td width="150">序列号</td>
              <td>{{ infoOption ? infoOption.sn : '' }}</td>
            </tr>
            <tr class="pure-table-odd">
              <td>IP地址</td>
              <td>{{ deviceIp }}</td>
              <td>连接类型</td>
              <td>WebSocket Client</td>
            </tr>
          </table>
        </div>
        <div class="deviceLine"><span></span>设备应用</div>
        <el-form label-width="120px" ref="editForm">
          <el-row>
            <el-col :span="12">
              <el-form-item label="Host:" prop="name">
                <el-input placeholder="填写设备Host" v-model="formData.host"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="端口号:" prop="id_code">
                <el-input placeholder="填写设备端口号，如8080" v-model="formData.port"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备范围:" prop="id_code">
                <el-input placeholder="设备范围" v-model="formData.rssi" class="w-100"></el-input>
                <el-popover
                    placement="right"
                    width="270"
                    trigger="click">
                  <el-table :data="rssiList"
                            :stripe="true"
                            :border="true">
                    <el-table-column property="default" label="默认" align="center"></el-table-column>
                    <el-table-column property="stable" label="稳定" align="center"></el-table-column>
                    <el-table-column width="70" label="范围" align="center">
                      <template slot-scope="scope">
                        {{scope.row.label}}米
                      </template>
                    </el-table-column>
                  </el-table>
<!--                  <el-button slot="reference">参考数值</el-button>-->
                  <el-link type="primary" slot="reference">参考数值</el-link>
                </el-popover>
                <!--                <el-select v-model="formData.rssi" placeholder="请选择">-->
                <!--                  <el-option-->
                <!--                      v-for="item in minrssi"-->
                <!--                      :key="item.value"-->
                <!--                      :label="item.label+'米'"-->
                <!--                      :value="item.value">-->
                <!--                  </el-option>-->
                <!--                </el-select>-->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="请求间隔:" prop="id_code">
                <el-input placeholder="请求间隔" v-model="formData.timeinit" class="w-140 mr-5"></el-input>
                秒
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="重复过滤器:" prop="id_code">
                <el-select v-model="formData.dup" placeholder="请选择">
                  <el-option
                      v-for="item in DuplicateList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="广播过滤器:" prop="id_code">
                <el-select v-model="formData.adv" placeholder="请选择">
                  <el-option
                      v-for="item in advList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="扫描模式:" prop="id_code">
                <el-select v-model="formData.scan" placeholder="请选择">
                  <el-option
                      v-for="item in scanList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
            </el-col>
          </el-row>
        </el-form>
        <div class="deviceLine"><span></span>设备网络</div>
        <el-form label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="Wi-Fi类型:">
                <el-input placeholder="wifi类型" v-model="wifitype" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Wi-Fi名称:">
                <el-input placeholder="Wi-Fi名称" v-model="netWorkOption.ssid" class="w-140 mr-5"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Wi-Fi密码:">
                <el-input placeholder="Wi-Fi密码" v-model="netWorkOption.passcode" class="w-140 mr-5"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="popupbody-footer">
        <el-button size="small" @click="closePOpup">返回</el-button>
        <el-button type="primary" size="small" @click="netWorkFn()" :disabled="loading?true:false">保存网络设置</el-button>
        <el-button type="primary" size="small" @click="saveDeviceFn()" :disabled="loading?true:false">保存应用设置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {rssiList} from '@/utils/util.js'
const os = require('os'); //操作系统
const request = require('request');

export default {
  name: 'studentMultiple',
  props: ['visible', 'deviceId'],
  data() {
    return {
      dialogVisible: this.visible,
      value: '',
      successInfo: '',
      erroInfo: '',
      loading: true,
      deviceOption: null,
      rssiList:rssiList,
      infoOption: null, // 硬件设备信息
      deviceIp: 0,
      // 扫描模式
      scanList: [
        {
          value: 0,
          label: '被动模式'
        },
        {
          value: 1,
          label: '主动模式'
        }
      ],
      // 重复过滤器
      DuplicateList: [
        {
          value: 0,
          label: '关闭'
        },
        {
          value: 1,
          label: '开启'
        }
      ],
      // 公共过滤器
      advList: [
        {
          value: 0,
          label: '允许所有数据'
        },
        {
          value: 1,
          label: '仅iBeacon'
        },
        {
          value: 2,
          label: '仅限Eddystone UID'
        },
        {
          value: 3,
          label: '仅限Eddystone URL'
        }
      ],
      // 范围
      minrssi: [
        {
          value: -127,
          label: 0
        },
        {
          value: -51,
          label: 0.5
        },
        {
          value: -60,
          label: 1
        },
        {
          value: -63,
          label: 2
        },
        {
          value: -66,
          label: 3
        },
        {
          value: -68,
          label: 4
        },
        {
          value: -70,
          label: 5
        },
        {
          value: -72,
          label: 6
        },
        {
          value: -74,
          label: 7
        },
        {
          value: -76,
          label: 8
        },
        {
          value: -78,
          label: 9
        },
        {
          value: -80,
          label: 10
        },
        {
          value: -82,
          label: 11
        },
        {
          value: -84,
          label: 12
        },
        {
          value: -86,
          label: 13
        },
        {
          value: -88,
          label: 14
        },
        {
          value: -90,
          label: 15
        }
      ],
      formData: {

        host: '', // host
        rssi: -127, // 范围
        port: '', // 端口号
        timeinit: '', // 推送时间
        adv: 0,// 公共过滤
        scan: 0,// 扫描模式
        dup: 0// 重复过滤器
      },
      wifitype: 'WPA-PSK/WPA2-PSK',
      // 网络
      netWorkOption: {
        'wifi-type': 0, // wifi-type
        ssid: '', // Wi-Fi SSID
        passcode: '', //Security Key
      },
      cancel: null,
      updateTime: null
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      console.log('this.visible:', this.visible)
      if (this.visible) {
        console.log('数据清理选中:', this.dynamicTagsArray)
        this.InitFn()
      } else {
        this.cancel('cancel')
        this.successInfo = '';
        this.erroInfo = '';
        this.formData = this.getJsonFn({
          host: '', // host
          rssi: -127, // 范围
          port: '', // 端口号
          timeinit: '', // 推送时间
          adv: 0,// 公共过滤
          scan: 0,// 扫描模式
          dup: 0// 重复过滤器
        });
        this.netWorkOption = this.getJsonFn({
          'wifi-type': 0,
          ssid: '',
          passcode: '',
        });
        this.loading = true
        clearInterval(this.updateTime)
      }
    }
  },
  created() {
  },
  methods: {
    // 保存应用设置
    saveDeviceFn() {
      // "http://" + nodeIp + "/config",
      let n = this;
      let dataOption = {
        'conn-type': 1,
        'req-format': 1,
        'min-rssi': this.formData.rssi, // 距离
        'http-host': this.formData.host,
        'ws-host': this.formData.host,
        'mqtt-host': this.formData.host, // host
        'ws-port': this.formData.port, // 端口
        'req-int': this.formData.timeinit, // 推送间隔
        'adv-filter': this.formData.adv,// 公共过滤
        'scan-act': this.formData.scan,// 扫描模式
        'dup-filter': this.formData.dup// 重复过滤器
      }
      this.axios
          .post('http://' + n.deviceIp + '/config', dataOption)
          .then(response => {
            console.log('成功：', response)
            n.submitFormAdd();
          })
          .catch(response => {
            console.log('=======================失败了：', response)
            n.$message.success('设置失败')
          })
    },
    // 保存网络设置
    netWorkFn() {
      let n = this;
      let dataOption = {
        'wifi-type': this.netWorkOption['wifi-type'], //
        'ssid': this.netWorkOption.ssid,
        'passcode': this.netWorkOption.passcode
      }
      this.axios
          .post('http://' + n.deviceIp + '/connection', dataOption)
          .then(response => {
            console.log('成功：', response)
            n.$message.success('设置成功！')
          })
          .catch(response => {
            console.log('=======================失败了：', response)
            n.$message.success('设置失败')
          })
    },
    // 提交保存服务器
    async submitFormAdd() {
      let n = this;
      let editForm = {
        name: '', // 名称
        code: '', // 设备号
        data: JSON.stringify(this.infoOption),
        scope: this.formData.rssi, // 范围
        id_code: this.deviceOption.data.mac, // 硬件号
        id: this.deviceId
      } // 编辑界面数据
      this.$post(this.api.admin_facility_edit, editForm).then((response) => {
        if (!response.code) {
          n.$message.success('设置成功')
          n.$emit('InitFn')
        } else {
          n.$message.success('请求接口失败')
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取服务器信息
    InitFn() {
      let n = this;
      this.$fetch(this.api.admin_facility_edit, {
        id: this.deviceId
      }).then((response) => {
        if (!response.code) {
          response.vo.data = JSON.parse(response.vo.data)
          n.deviceOption = JSON.parse(JSON.stringify(response.vo));
          n.deviceIp = response.vo.ip;
          n.getInfomation(); // 获取应用设备设置信息
          n.deviceInfoFn(); // 获取硬件设备信息
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 关闭弹窗
    closePOpup() {
      this.$emit('update:visible', false)
    },
    // 获取id内盒子信息
    getInfomation() {
      let CancelToken = this.axios.CancelToken
      let n = this;
      this.axios
          .get('http://' + n.deviceIp + '/config.json', {
            cancelToken: new CancelToken(function executor(c) {
              n.cancel = c // 这个参数 c 就是CancelToken构造函数里面自带的取消请求的函数，这里把该函数当参数用
            })
          })
          .then(response => {
            console.log('设备回执：', response)
            if (response) {
              n.formData.host = response.data.host;
              n.formData.rssi = response.data['min-rssi'];
              n.formData.port = response.data.port;
              n.formData.timeinit = response.data['req-int'];
              n.formData.adv = response.data['adv-filter'];
              n.formData.scan = response.data['scan-act'];
              n.formData.dup = response.data['dup-filter'];
              n.successInfo = '设备应用连接成功';
              this.getNetWorkFn()
            }
          })
          .catch(response => {
            console.log('设备应用=======================responseerr：', response)
            console.log('response:', response.message)
            if (response.message !== 'cancel') {
              n.$message.error('设备连接失败，查看设备网络是否正常')
              n.erroInfo = '获取设备应用失败，查看设备网络是否正常，设备ip是否变更'
              n.loading = false
            }
          })
    },
    async deviceInfoFn() {
      let n = this;
      let {data} = await this.axios.get('http://' + n.deviceIp + '/info', {})
      n.infoOption = data
      console.log('获取硬件设备信息：', data)
    },
    getNetWorkFn() {
      let n = this;
      this.axios
          .get('http://' + n.deviceIp + '/connection', {})
          .then(response => {
            console.log('设备网络回执：', response)
            if (response) {
              n.netWorkOption.host = response.data['wifi-type'];
              n.netWorkOption.ssid = response.data['ssid'];
              n.netWorkOption.passcode = response.data['passcode'];
              n.successInfo = '设备应用连接成功，设备网络连接成功';
              n.loading = false
            }
          })
          .catch(response => {
            console.log('=======================responseerr：', response)
            n.$message.error('获取设备网络失败')
            n.erroInfo = '获取设备网络失败，查看设备网络是否正常，更新设备ip'
            n.loading = false
          })
    },
    // 刷新设备连接
    refreshFn() {
      this.erroInfo = '';
      this.loading = true;
      this.getInfomation();
    },
    getJsonFn(option) {
      return JSON.parse(JSON.stringify(option))
    },
    // 更新硬件设备
    async updateDevice() {
      // alert('update', JSON.stringify($("form#f-update").serialize()))
      let dataLoad = await this.axios.post('http://' + this.deviceIp + '/update', {'ota-update': 1})
      let n = this;
      console.log(dataLoad)
      clearInterval(n.updateTime)
      this.updateTime = setInterval(() => {
        this.axios.get('http://' + this.deviceIp + '/ota', {
          params: {t: (new Date().getTime())}
        })
            .then(data => {
              // resolve(response.data)
              console.log('设备data', data)
              if (data.data.status === 1) {
                console.log('继续更新')
              } else {
                console.log('关闭跟新')
                n.$message.success('更新成功')
                clearInterval(n.updateTime)
                n.deviceInfoFn() // 获取新版本
              }
            })
            .catch(err => {

            })
      }, 3000)
    },
    // 重启当前设备
    async restartFn(){
      let {data} = await this.axios.post('http://' + this.deviceIp + '/restart', {"restart": 1})
      console.log('重启:',data)
      if(data==='ok'){
        this.$message.success('重启成功')
      }
    }
  },
  mounted() {
  }
}
</script>
<style scoped>
table {
  border-collapse: collapse;
  border-spacing: 0;
}

.table-box {
  border: 1px solid #cbcbcb;
  margin-bottom: 20px;
}

td, th {
  padding: 15px 10px !important;
}

pure-table {
  border-collapse: collapse;
  border-spacing: 0;
  empty-cells: show;
  border: 1px solid #cbcbcb
}

.pure-table caption {
  color: #000;
  font: italic 85%/1 arial, sans-serif;
  padding: 1em 0;
  text-align: center
}

.pure-table td, .pure-table th {
  border-left: 1px solid #cbcbcb;
  border-width: 0 0 0 1px;
  font-size: inherit;
  margin: 0;
  overflow: visible;
  padding: .5em 1em
}

.pure-table td:first-child, .pure-table th:first-child {
  border-left-width: 0
}

.pure-table thead {
  background-color: #e0e0e0;
  color: #000;
  text-align: left;
  vertical-align: bottom
}

.pure-table td {
  background-color: transparent
}

.pure-table-odd td {
  background-color: #f2f2f2
}

.pure-table-striped tr:nth-child(2n-1) td {
  background-color: #f2f2f2
}

.pure-table-bordered td {
  border-bottom: 1px solid #cbcbcb
}

.pure-table-bordered tbody > tr:last-child > td {
  border-bottom-width: 0
}

.pure-table-horizontal td, .pure-table-horizontal th {
  border-width: 0 0 1px;
  border-bottom: 1px solid #cbcbcb
}

.pure-table-horizontal tbody > tr:last-child > td {
  border-bottom-width: 0
}

.deviceLine {
  display: flex;
  align-items: center;
  background: #f8f8f8;
  padding: 5px;
  margin-bottom: 10px;
}

.deviceLine span {
  display: block;
  width: 3px;
  height: 14px;
  border-radius: 2px;
  background: #006dcd;
  margin-right: 5px;
}

.popupbody-boxin {
  min-width: 850px;
}

#cont-ver {
  display: flex;
  align-items: center;
}
</style>
